package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;
    //上传排班
    @Override
    public void save(Map<String, Object> paramMap) {
        //1、封装参数数据
        //把map转化成json字符串
        String hospJsonStr = JSONObject.toJSONString(paramMap);
        //把json字符串转化成对象
        Schedule schedule = JSONObject.parseObject(hospJsonStr, Schedule.class);

        //2、根据医院编码、排班编码查询排班信息
        Schedule scheduleExist = scheduleRepository
                .getScheduleByHoscodeAndHosScheduleId(
                        schedule.getHoscode(),schedule.getHosScheduleId()
                );
        //判断
        if(scheduleExist!=null){
            //更新
            schedule.setId(scheduleExist.getId());
            schedule.setCreateTime(scheduleExist.getCreateTime());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);

        }else{
            //新增
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }

    }

    //根据医院编号和科室编号查询排班规则数据（mongoTemplate分页带条件分组查询数据库）
    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hoscode, String depcode) {
        //1,根据查询，分页统计查询规则数据
        //1.1设置查询条件
        Criteria criteria=  Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //1.2分组统计
        Aggregation agg=Aggregation.newAggregation(
                //1.3匹配筛选条件
                Aggregation.match(criteria),
                //1.4分组统计
                Aggregation.group("workDate")//分组字段
                //分组统计的结果
                .first("workDate").as("workDate")
                //统计医生数量
                .count().as("docCount")
                //计算号源数量相加
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                //1.5排序
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                //1.6分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //分组查询
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        //得到带分页的集合
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregate.getMappedResults();

        //2,根据查询条件， 查询统计规则数据的总数（获取total）
        Aggregation totalAgg=Aggregation.newAggregation(
                //匹配查询条件
                Aggregation.match(criteria),
                //分组
                Aggregation.group("workDate")
        );
        //分组查询
        AggregationResults<BookingScheduleRuleVo> aggregateTotal = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoTotal = aggregateTotal.getMappedResults();
        int total = bookingScheduleRuleVoTotal.size();

        //3,借助工具算出周几
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayForWeek=this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayForWeek);
        }
        //4 封装数据
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);
        // 数据补全
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);
        return result;
    }

    //根据医院编号和科室编号查询排班规则数据
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //1.把字符串workDate转换成Date类型
        Date workDateToDate = new DateTime(workDate).toDate();
        //2.调用接口方法查询数据
        List<Schedule> scheduleList=
        scheduleRepository.getScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,workDateToDate);
        //3.根据编码查询具体名称用于展示
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);

        });

        return scheduleList;


    }

    //获取可预约排班数据
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        //1获取医院挂号预约规则
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        if(hospital==null){
            throw  new YyghException(20001,"医院信息有误");
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //2获取可以预约的日期分页数据：返回值Ipage<Date>,参数page，limit
        IPage<Date> iPage = this.getListDate(page,limit,bookingRule);
        List<Date> dateList = iPage.getRecords();

        //3根据查询，分页、统计查询规则数据
        //设置查询条件
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);
        //1.2 分组统计
        Aggregation agg = Aggregation.newAggregation(
                //1.3匹配筛选条件
                Aggregation.match(criteria),
                //1.4分组统计
                Aggregation.group("workDate")//分组字段
                        //分组统计结果
                        .first("workDate").as("workDate")
                        //统计医生数量
                        .count().as("docCount")
                        //号源数量相加
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber")

        );
        AggregationResults<BookingScheduleRuleVo> aggregate =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList =
                aggregate.getMappedResults();
        //统计规则数据封装成一个map
        Map<Date,BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleVoList)){
            scheduleVoMap = scheduleVoList.stream()
                    .collect(Collectors.toMap(
                            BookingScheduleRuleVo::getWorkDate,
                            BookingScheduleRuleVo->BookingScheduleRuleVo
                    ));
        }
        //4合并数据 1 可以预约的日期dateList 2 统计排班数据scheduleVoMap
        List<BookingScheduleRuleVo> bookingScheduleList = new ArrayList<>();
        for (int i = 0,len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //bookingScheduleRuleVo为空，此科室在date这天没有排班
            if(bookingScheduleRuleVo==null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);

            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            //最后一页，最后一条记录为即将预约 状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i==len-1 && page == iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else{
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天如果过了停号时间，也不能预约
            if(i==0&&page==1){
                //停号时间
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }

            bookingScheduleList.add(bookingScheduleRuleVo);
        }

        //5最后封装，所有数据封装到map
        //可以预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);

        return result;
    }


    //根据id查询排班详情
    @Override
    public Schedule getScheduleById(String id) {
        Schedule schedule = this.packageSchedule(scheduleRepository.findById(id).get());


        return schedule;
    }

    //根据排班id获取预约下单数据
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo=new ScheduleOrderVo();
        //获取排班信息
        Schedule schedule = this.getScheduleById(scheduleId);
        if(schedule==null){
            throw new YyghException(20001,"排班信息有误");
        }
        //获取预约规则信息
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        if(hospital==null){
            throw new YyghException(20001,"医院信息有误");
        }
        //获取预约规则
        BookingRule bookingRule = hospital.getBookingRule();
        if(bookingRule==null){
            throw new YyghException(20001,"医院挂号规则有误");
        }
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());
        //退号截止天数 （例如：就诊前一天为-1，当天为0）
        Integer quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(
                new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(),
                bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(stopTime.toDate());
        return scheduleOrderVo;

    }
    //修改排班
    @Override
    public void update(Schedule schedule) {
        scheduleRepository.save(schedule);
    }

    //根据医院id和订单id查询排班详情
    @Override
    public Schedule getScheduleByIds(String hoscode, String hosScheduleId) {

        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        return schedule;
    }


    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
    //获取可以预约日期分页数据
    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //获取当前日期的预约时间（日期加时间）
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //判断当前时间是否已经过了时间限制，如果过了 周期加一天
        if(releaseTime.isBeforeNow()) cycle+=1;
        //封装可预约时间
        List<Date> dateList=new ArrayList<>();
        for (Integer i = 0; i < cycle; i++) {
            //计算当前可预约的日期
            DateTime dateTime = new DateTime().plusDays(i);
            String dateString = dateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排显示7条数据 ，多了进行分页
        List<Date> pageDateList=new ArrayList<>();
        int start=(page-1)*limit;
        int end=(page-1)*limit+limit;
        if(end>dateList.size())end=dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage=new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                page,7,dateList.size()
        );
        iPage.setRecords(pageDateList);
        return iPage;



    }
    //3根据编码查询具体名称用于展示
    private Schedule packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",
                departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;

    }


    //借助工具计算出周几
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }




    }
